package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.Map;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import process.*;
import databaseAcces.*;

/**
 * Servlet implementation class ControllerUser
 */
public class ControllerUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static String DELETE_JSP = "/Delete.jsp";
	private static String EDIT_JSP = "/Edit.jsp";
	private static String SHOWALL_JSP = "/ShowAll.jsp";

       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ControllerUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String forward="";
		// Get a map of the request parameters
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		Enumeration<String> e = request.getParameterNames();
		
			
		//On parcours cette liste
				while(e.hasMoreElements()){
					String key = e.nextElement();
					//System.out.println("key = "+key);
						out.println("<p><strong> "+key+"</strong></p>");			
				}
				@SuppressWarnings("unchecked")
				Map parameters = request.getParameterMap();
				if (parameters.containsKey("delete")){
					forward = DELETE_JSP;
				} else if (parameters.containsKey("edit")){
					forward = EDIT_JSP;
				} else {
					forward = SHOWALL_JSP;
				}
				RequestDispatcher view = request.getRequestDispatcher(forward);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		Init_Session(request);
		
		
		String forward="";
		// Get a map of the request parameters
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		Enumeration<String> e = request.getParameterNames();
		// name=login;password= type= candidat ou entreprise 
		String login = request.getParameter("name");
		String password = request.getParameter("c_password");
		String type = "2";
		String var = request.getParameter("type");
		if (!var.equals(""))  
			type = request.getParameter("type");
		// request.getParameter("type");
		JobManagement chek = new JobManagement();
		HttpSession session = request.getSession();
		if (login.equals(password)) {
		 session.setAttribute("login", login);
		// session.setAttribute("type", type);
		//**		 
		if (chek.verifyUser(login, password, type) == 0 ) {
			if ((type.equals("1")) || (type.equals("0"))) {
				
				System.out.println("PASS 0");
					session.setAttribute("createlogin", login);
					response.sendRedirect("SignIn.jsp");	
			}
			else {
				
				// acc entreprise et candidat existe			
				
				/// faut dire si c'est le home de candidat ou entreprise
			//	check.getLoginInformations(login,password);
			  LinkedList<String> listInfos = chek.getInformations(login, password);
			  
			  
		  		//	listInfos[0]:"Id"  
		  		//	listInfos[1]:"login" 
		  		//	listInfos[2]:"password" 
		  		//	listInfos[3]:"type" 
			  session.setAttribute("type",listInfos.get(3));
			  session.setAttribute("num_user",listInfos.get(0));	  
			  	
				// mise jours les information
				Update_Session(request);			 
				response.sendRedirect("Home.jsp");
			}
		//	out.println(" user deja enregistrer");
		}
		else {
			
		
			if (type.equals("2")) {
				 session.setAttribute("userlogin", login);
				 response.sendRedirect("SignIn.jsp");	
			} else {
				
				// recuperer les nouvelles infos 
				  LinkedList<String> Infos = chek.getInformations(login, password);
				  session.setAttribute("type",Infos.get(3));
				  session.setAttribute("num_user",Infos.get(0));
				
				
				// afficher CVManagement ou JobManagemant
				if (type.equals("1"))
				{		
		
				 response.sendRedirect("CompanyManagement.jsp");
				}
				if (type.equals("0"))
				{			
					 response.sendRedirect("CVManagement.jsp");
				}
				
			}
			
		}
			//On parcours cette liste
				while(e.hasMoreElements()){
					String key = e.nextElement();
					//System.out.println("key = "+key);
						out.println("<p><strong> "+key+"</strong></p>");			
				}
				@SuppressWarnings("unchecked")
				Map parameters = request.getParameterMap();
				if (parameters.containsKey("delete")){
					forward = DELETE_JSP;
				} else if (parameters.containsKey("edit")){
					forward = EDIT_JSP;
				} else {
					forward = SHOWALL_JSP;
				}
				RequestDispatcher view = request.getRequestDispatcher(forward);
		} else
			response.sendRedirect("SignIn.jsp");	
	}

	private void Init_Session(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		
				
		//***************** Initia les session pour candidat *********************//		
		session.setAttribute("num_Ca",null);
		session.setAttribute("name",null);
		session.setAttribute("date_birth",null);
		session.setAttribute("salary_wanted",null);
		session.setAttribute("levelstudy",null);				
		session.setAttribute("sex",null);						
		session.setAttribute("languages",null);
		session.setAttribute("year_experience",null);
		session.setAttribute("position_wanted",null);
	
		
		//************************** Initia les session pour entreprise ************//
		session.setAttribute("num_En",null);
		session.setAttribute("nom_En",null);		
		session.setAttribute("num_Po",null);				
		session.setAttribute("titre",null);		
		session.setAttribute("salaire_propose",null);
		session.setAttribute("experience_requis",null);
		session.setAttribute("lieu_travail",null);
		session.setAttribute("niveau",null);
		session.setAttribute("date_limte",null);	
		
		
		//**************************** les valeurs commus ***********************//
		session.setAttribute("web_site",null);
		session.setAttribute("address",null);
		session.setAttribute("phone",null);
		session.setAttribute("email",null);	
		session.setAttribute("description",null);
		session.setAttribute("specialite",null);		
		session.setAttribute("domain",null);
		session.setAttribute("description",null);				
		
	}
	@SuppressWarnings("unused")
	private void Update_Session(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		String type =  (String)session.getAttribute("type");
		
		// type : 
		// 0 : le candidat 
		// 1 : l'entreprise
		
		if (type.equals("0"))
		{
			Update_Session_Candidat(request);
		}
		else
		{
			Update_Session_Entre(request);
		}
	}
	
	private void Update_Session_Candidat(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		
		DisplayRequest dis = new DisplayRequest();
		Vector<String> parametre_Candidat = new Vector<String>();
		
		int num_user = Integer.parseInt((String)session.getAttribute("num_user"));	
		parametre_Candidat = dis.getCandidature_user(num_user);
		
		
		// S'il a enregistre le CV, nous allons sauvegarder dans les sessions
		if(parametre_Candidat.size() > 0){
			// pour la table candidat 
			session.setAttribute("name",parametre_Candidat.elementAt(1));
			session.setAttribute("web_site",parametre_Candidat.elementAt(2));
			session.setAttribute("address",parametre_Candidat.elementAt(3));
			session.setAttribute("phone",parametre_Candidat.elementAt(4));
			session.setAttribute("email",parametre_Candidat.elementAt(5));	
			session.setAttribute("date_birth",parametre_Candidat.elementAt(6));
			session.setAttribute("salary_wanted",parametre_Candidat.elementAt(7));
			session.setAttribute("levelstudy",parametre_Candidat.elementAt(8));						
			session.setAttribute("sex",parametre_Candidat.elementAt(9));					
			session.setAttribute("description",parametre_Candidat.elementAt(10));
			session.setAttribute("languages",parametre_Candidat.elementAt(11));	
			
			
			// pour l'experience
			LinkedList<String> experience = new LinkedList<String>();
			
			parametre_Candidat.removeElementAt(0);
			int num_Ca = dis.getNum_Candidatures(parametre_Candidat);
			session.setAttribute("num_Ca",num_Ca +"");
			
			
			experience = dis.getExperienceCandiate(num_Ca);
			
			//experience[0] :"num_Ca" 
	   		//experience[1]: "num_experien" 
	   		//experience[2] : "nom_Poste_Exerce"
	   		//experience[3] :"specialite" 
	   		//experience[4] : "domaine" 	
			session.setAttribute("year_experience",experience.get(1));
			session.setAttribute("position_wanted",experience.get(2));
			session.setAttribute("specialite",experience.get(3));		
			session.setAttribute("domain",experience.get(4));
				
		}		
				
	}
	
	private void Update_Session_Entre(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		
		DisplayRequest dis = new DisplayRequest();
		Vector<String> parametre_En = new Vector<String>();
		
		int num_user = Integer.parseInt((String)session.getAttribute("num_user"));	
		parametre_En = dis.getCompany_user(num_user);
		
		// S'il a enregistre le CV, nous allons sauvegarder dans les sessions
		if(parametre_En.size() > 0 )
		{
			// ********************** Pour la table d'Entreprise *********************//			
			//parametre_En [0]: "num_En"		   				
			//parametre_En [1]: "nom_En"
			//parametre_En [2]: "web_site"
			//parametre_En [3]: "adresse"
			//parametre_En [4]: "telephone"
			//parametre_En [5]: "courriel"	   					
			//parametre_En [6]: "description"
			//parametre_En [7]: "num_user" ; deja active dessous
			
			session.setAttribute("num_En",parametre_En.elementAt(0));			
			session.setAttribute("name",parametre_En.elementAt(1));
			session.setAttribute("web_site",parametre_En.elementAt(2));
			session.setAttribute("address",parametre_En.elementAt(3));
			session.setAttribute("phone",parametre_En.elementAt(4));
			session.setAttribute("email",parametre_En.elementAt(5));						
			session.setAttribute("description",parametre_En.elementAt(6));
			
			
			// ********************** Pour la table de Poste *********************//
			
			// Nous allons verifier que ce company a  enregistre la Poste 
			// Si Oui : Nous mettons les sessions 
			// Si Non : Ne rien faire
			int num_En = Integer.parseInt(parametre_En.elementAt(0));
			Vector<String> parametre_Pos = new Vector<String>();
			parametre_Pos = dis.getPoste_num_En(num_En);
			
			// il a enregistre la poste 
			if(parametre_Pos.size() > 0)
			{
				// Mise a jours les sessions 
				//[0]:"num_Po"	
   				//[1]:"titre"		   				
				//[2]:"specialite"
				//[3]:"domaine"   						
				//[4]:"salaire_propose" 					
				//[5]:"experience_requis"
				//[6]:"lieu_travail"	   					
				//[7]:"niveau"
				//[8]:"description"	   					
				//[9]: "num_En"
				//[10]:"date_limte"
							
				
				session.setAttribute("num_Po",parametre_Pos.elementAt(0));
				session.setAttribute("position_wanted",parametre_Pos.elementAt(1));
				session.setAttribute("specialite",parametre_Pos.elementAt(2));
				session.setAttribute("domain",parametre_Pos.elementAt(3));
				session.setAttribute("salary_wanted",parametre_Pos.elementAt(4));
				session.setAttribute("year_experience",parametre_Pos.elementAt(5));
				session.setAttribute("lieu_travail",parametre_Pos.elementAt(6));
				session.setAttribute("levelstudy",parametre_Pos.elementAt(7));
				session.setAttribute("description_job",parametre_Pos.elementAt(8));				
				session.setAttribute("date_limite",parametre_Pos.elementAt(10));	
									
			}
			
		}
		
	}

}
